//
//  ProfileOneViewController.m
//  HTP
//
//  Created by 陈钱钿 on 15/10/31.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "ProfileOneViewController.h"
#import "ProfileModel.h"
#import "UserVM.h"
#define cellHeight 44
#define IconWH 70
#define kBorder 10
@interface ProfileOneViewController () <UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UITextField *nameField;
@property (nonatomic, retain) UITextField *schoolField;
@property (nonatomic, retain) UITextField *ageField;
@property (nonatomic, retain) UITextField *mottoField;
@property (nonatomic, retain) UITextField *sexField;
@property (nonatomic, retain) UITextField *addAddressField;
@property (nonatomic, retain) UILabel *getLocationLabel;
@property (nonatomic, retain) UIDatePicker *datePicker;
@property (nonatomic, retain) NSString *date; //读取选择年龄时的日期
@property (nonatomic, retain) UIButton *head_icon;
@property (nonatomic, retain) ProfileModel *profileModel;
@property (nonatomic, assign) double latitude;//纬度
@property (nonatomic, assign) double longitude;//经度

@property (nonatomic,retain) UITextField *editTextField;
@end

@implementation ProfileOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTop];
    [self initUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [self addCustomBackBase];
    self.profileModel = [ProfileModel mj_objectWithKeyValues:[USERCONTENT getDefaultUser]];
    [self setData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //移除通知响应
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification];
}

- (UIDatePicker *)datePicker {
    if(!_datePicker) {
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.backgroundColor = [UIColor redColor];
    }
    return _datePicker;
}





//TODO:初始化导航栏
- (void)initTop {
    [self addCustomTitleWithTitle:@"基本信息"];
    self.navigationItem.rightBarButtonItem = nil;
}


//TODO:绘制UI
- (void)initUI{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeihgt)];
    self.scrollView.userInteractionEnabled = YES;
    [self.view addSubview:self.scrollView];
    
    UIImage *lineImage = [UIImage imageNamed:@"line"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeihgt/5)];
    self.head_icon = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-IconWH)/2, (headView.frame.size.height-IconWH)/2, IconWH, IconWH)];
    [self.head_icon setImage:[UIImage imageNamed:@"head_icon"] forState:UIControlStateNormal];
    [self.head_icon addTarget:self action:@selector(changeIcon) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.head_icon];
    UIImageView *line1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, headView.frame.size.height, ScreenWidth, 1)];
    line1.image = lineImage;
    [headView addSubview:line1];
    [self.scrollView addSubview:headView];
    
    UIView *nameView = [[UIView alloc] initWithFrame:CGRectMake(0, headView.frame.size.height, ScreenWidth, cellHeight)];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, 0, 60, cellHeight)];
    nameLabel.text = @"姓 名";
    [nameView addSubview:nameLabel];
    self.nameField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(nameLabel.frame), 2, ScreenWidth-60, cellHeight)];
    self.nameField.delegate = self;
    self.nameField.tag = 0;
    [nameView addSubview:self.nameField];
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, nameView.frame.size.height, ScreenWidth, 1)];
    line2.image = lineImage;
    [nameView addSubview:line2];
    [self.scrollView addSubview:nameView];
    
    UIView *sexView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(nameView.frame)+2, ScreenWidth, cellHeight)];
    UILabel *sexLabel = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, 0, 60, cellHeight)];
    sexLabel.text = @"性 别";
    [sexView addSubview:sexLabel];
    self.sexField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(sexLabel.frame), 1, 150, cellHeight)];
    self.sexField.tag = 1;
    self.sexField.delegate = self;
    [sexView addSubview:self.sexField];
    UIImageView *line3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, sexView.frame.size.height, ScreenWidth, 1)];
    line3.image = lineImage;
    [sexView addSubview:line3];
    [self.scrollView addSubview:sexView];
    
    UIView *ageView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(sexView.frame)+1, ScreenWidth, cellHeight)];
    UILabel *ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, 0, 60, cellHeight)];
    ageLabel.text = @"年 龄";
    [ageView addSubview:ageLabel];
    self.ageField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(ageLabel.frame), 1, ScreenWidth-60, cellHeight)];
    self.ageField.tag = 2;
    self.ageField.delegate = self;
    [ageView addSubview:self.ageField];
    
    UIImageView *line4 = [[UIImageView alloc] initWithFrame:CGRectMake(0, ageView.frame.size.height, ScreenWidth, 1)];
    line4.image = lineImage;
    [ageView addSubview:line4];
    [self.scrollView addSubview:ageView];
    
    
    UIView *addressView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(ageView.frame)+1, ScreenWidth, 2*cellHeight)];
    UILabel *addressLable = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, cellHeight/2, 60, cellHeight)];
    addressLable.text = @"地 址";
    [addressView addSubview:addressLable];
    UIButton *addressBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(addressLable.frame)+20, 6, 30, 30)];
//    [addressBtn addTarget:self action:@selector(getAddress) forControlEvents:UIControlEventTouchUpInside];
    [addressBtn setImage:[UIImage imageNamed:@"address"] forState:UIControlStateNormal];
    [addressView addSubview:addressBtn];

    self.getLocationLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(addressBtn.frame)+3, 0, 170, cellHeight)];
    self.getLocationLabel.text = @"获取定位信息";
    self.getLocationLabel.font = [UIFont systemFontOfSize:14];
    [self.getLocationLabel setTextColor:[UIColor grayColor]];
    [addressView addSubview:self.getLocationLabel];
    
    UIButton *forwardBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.getLocationLabel.frame), kBorder+1, 15, 20)];
    [forwardBtn setImage:[UIImage imageNamed:@"forward"] forState:UIControlStateNormal];
    [addressView addSubview:forwardBtn];
    UIImageView *middleLine = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(addressLable.frame)+20, cellHeight+1, ScreenWidth-CGRectGetMaxX(addressLable.frame)-20, 1)];
    middleLine.image = lineImage;
    [addressView addSubview:middleLine];
    
    self.addAddressField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(addressLable.frame)+20, cellHeight+1, 240, cellHeight)];
    self.addAddressField.delegate = self;
    self.addAddressField.tag = 3;
    self.addAddressField.placeholder = @"补充详细地址（如门牌号/楼层号等）";
    [self.addAddressField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.addAddressField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [addressView addSubview:self.addAddressField];
    UIImageView *line6 = [[UIImageView alloc] initWithFrame:CGRectMake(0, addressView.frame.size.height, ScreenWidth, 1)];
    line6.image = lineImage;
    [addressView addSubview:line6];
    [self.scrollView addSubview:addressView];
    
    UIView *schoolView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(addressView.frame)+2, ScreenWidth, cellHeight)];
    UILabel *schoolLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, 0, 60, cellHeight)];
    schoolLabel1.text = @"所在学校";
    schoolLabel1.font = [UIFont systemFontOfSize:15];
    [schoolView addSubview:schoolLabel1];

    self.schoolField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(schoolLabel1.frame)+20, 1, ScreenWidth-60, cellHeight)];
    self.schoolField.delegate = self;
    self.schoolField.tag = 4;
    [schoolView addSubview:self.schoolField];
    UIImageView *line7 = [[UIImageView alloc] initWithFrame:CGRectMake(0, schoolView.frame.size.height+1, ScreenWidth, 1)];
    line7.image = lineImage;
    [schoolView addSubview:line7];
    [self.scrollView addSubview:schoolView];
    
    UIView *mottoView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(schoolView.frame)+1, ScreenWidth, cellHeight)];
    UILabel *mottoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kBorder, 0, 60, cellHeight)];
    mottoLabel.text = @"座右铭";
    [mottoView addSubview:mottoLabel];
    self.mottoField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mottoLabel.frame)+20, 1, ScreenWidth-60, cellHeight)];
    self.mottoField.tag = 5;
    self.mottoField.delegate = self;
    [mottoView addSubview:self.mottoField];
    UIImageView *line8 = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(mottoLabel.frame)+1, ScreenWidth, 0.8)];
    line8.image = lineImage;
    [mottoView addSubview:line8];
    [self.scrollView addSubview:mottoView];
    
}

//TODO:设置数据
- (void)setData {
    self.nameField.text = self.profileModel.prChildName;
    if([self.profileModel.prChildSex integerValue] == 1)
        self.sexField.text = @"男";
    else{
        self.sexField.text = @"女";
    }
    self.addAddressField.text = self.profileModel.prAddr;
    self.schoolField.text = self.profileModel.prChildSchool;
    self.mottoField.text = self.profileModel.prMotto;

    NSString *birYear = [self.profileModel.userBirth substringToIndex:4];
    NSString *nowYear = [self getNowYear];
    int age = [nowYear intValue] - [birYear intValue] + 1;
    self.ageField.text = [NSString stringWithFormat:@"%d",age];
    
    //设置datepicker选中的时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:DATEFORMATT];
    NSDate *date = [dateFormatter dateFromString:self.profileModel.userBirth];
//    self.datePicker.date = date;
    self.date = self.profileModel.userBirth;
}

/*
 当UITextFieldText DidBeginEditingNotification
 */

//点击右上角完成 触摸背景时 收回键盘
//TODO:完成按钮点击
/**
 *  个人信息完成修改后发送通知到root 修改左边头像
 */
//-(void)finishAction{
//    [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEPROFILE object:[NSDictionary dictionary]];
//}

//TODO:头像点击触发事件
- (void)changeIcon {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:self.view];
}

//TODO:actionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { //调用系统相机
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    } else if(buttonIndex == 1) { //调用系统相册
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

//TODO:imagePicker Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *imageData = info[@"UIImagePickerControllerEditedImage"];
    NSData *image = UIImageJPEGRepresentation(imageData, 0.3);
    //设置
    [self.head_icon setImage:imageData forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:^{
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    }];
}



//TODO:更新个人信息
- (void)updateProfile {
    UserVM *userVM = [[UserVM alloc] init];
    [userVM setBlockWithReturnBlock:^(id returnValue) {
        [self changeProfile];
        [self dismissSVProgress];
        self.navigationItem.rightBarButtonItems = nil;
    } WithErrorBlock:^(id errorCode) {
        [self showSVProgressFailed:@"保存失败"];
    } WithFailureBlock:^{
        [self showSVProgressFailed:INTERFACE_FAILURE_CHIN];
    }];
    NSNumber *prChildSex;
    if([self.sexField.text isEqualToString:@"男"]){
        prChildSex = [NSNumber numberWithInt:1];
    }else if([self.sexField.text isEqualToString:@"女"]){
        prChildSex = [NSNumber numberWithInt:2];
    }
    [userVM profileUpdate:[NSString stringWithFormat:@"%@",self.profileModel.prId] prChilrName:self.nameField.text prChildSex:[NSString stringWithFormat:@"%@",prChildSex] userBirth:self.date prChildSchool:self.schoolField.text prAddr:self.addAddressField.text prChildPhoto:@"" prMotto:self.mottoField.text];
}
-(void)changeProfile{
    NSString *prChildSex;
    if([self.sexField.text isEqualToString:@"男"]){
        prChildSex = @"1";
    }else if([self.sexField.text isEqualToString:@"女"]){
        prChildSex = @"2";
    }
    self.profileModel.prChildName = self.nameField.text;
    self.profileModel.prChildSex = [NSNumber numberWithInt:[prChildSex intValue]];
    self.profileModel.userBirth = self.date;
    self.profileModel.prChildSchool = self.schoolField.text;
    self.profileModel.prAddr = self.addAddressField.text;
    self.profileModel.prMotto = self.mottoField.text;
    NSDictionary *userDic = [[NSDictionary alloc] initWithDictionary:self.profileModel.mj_keyValues];
    [USERCONTENT setUserBean:userDic];
}









//TODO:点击datapick上的完成按钮
- (void)ageUpdate {
    //得到年月日
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:DATEFORMATT];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy"];
    
    NSString *nowYear = [self getNowYear];
    
    //要传的数据 yyyy-mm-dd格式的字符串
    self.date = [formatter stringFromDate:self.datePicker.date];
    //得到选择的年份
    NSString *selectedYear = [formatter1 stringFromDate:self.datePicker.date];
    
    int age = [nowYear intValue] - [selectedYear intValue]+1;
    self.ageField.text = [NSString stringWithFormat:@"%d",age];
}
//得到当前的年份
- (NSString *)getNowYear {
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy"];
    NSString *nowYear = [formatter1 stringFromDate:[NSDate date]];
    return nowYear;
}

//TODO:通知响应 键盘即将隐藏时调用
#pragma mark - keyboard
-(void) keyboardWillHiden:(NSNotification *)notification{
    [UIView animateWithDuration:0.5 animations:^{
        self.scrollView.frame = CGRectMake(0.0f, 0.0f, ScreenWidth, ScreenHeihgt - NavHe);
    }];
}
-(void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat bottom = CGRectGetMaxY(_editTextField.frame);
    CGFloat keyboardOffset = CGRectGetHeight(keyboardRect);
    int offset = bottom + keyboardOffset + 1.0 - ScreenHeihgt;
    if(offset>0){
        [UIView animateWithDuration:animationDuration animations:^{
            self.scrollView.frame = CGRectMake(0.0f, -offset, ScreenWidth, ScreenHeihgt);
        }];
    }
}
//TODO: textfield delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _editTextField = textField;
    if (textField.tag == 2 || textField.tag == 1) {
        return NO;
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
